package com.fire.control.system.module.security.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import com.fire.control.system.dto.SelectGroupDTO;
import com.fire.control.system.dto.UserDTO;
import com.fire.control.system.dto.UserInfo;
import com.fire.control.system.dto.UserResultDTO;
import com.fire.control.system.entity.Company;
import com.fire.control.system.entity.DeviceGroup;
import com.fire.control.system.entity.Role;
import com.fire.control.system.entity.User;
import com.fire.control.system.entity.UserDeviceGroup;
import com.fire.control.system.module.device.dao.DeviceGroupMapper;
import com.fire.control.system.module.device.dao.DeviceGroupRepository;
import com.fire.control.system.module.role.dao.RoleMapper;
import com.fire.control.system.module.security.dao.SecurityMapper;
import com.fire.control.system.module.security.dao.SecurityRepository;
import com.fire.control.system.module.security.dao.UserDeviceGroupRepositoty;
import com.fire.control.system.module.security.service.ISecurityService;
import com.fire.control.system.module.user.dao.UserMapper;
import com.fire.control.system.module.user.dao.UserRepository;
import com.fire.control.system.statics.ResponseMessage;
import com.fire.control.system.statics.Type_Role;
import com.fire.control.system.statics.Type_User;
import com.fire.control.system.support.protocol.comman.ProtocolSelector;
import com.fire.control.system.support.protocol.comman.ResponseProtocol;
import com.fire.control.system.support.protocol.security.SecurityRequestProtocol;
import com.fire.control.system.support.util.JSONUtil;
import com.fire.control.system.support.util.ResultPageUtil;
import com.fire.control.system.support.util.SmsUtil;
import com.fire.control.system.support.util.StaticValue;
import com.fire.control.system.support.util.XdaoDate;
import com.fire.control.system.support.util.XdaoPassword;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class SecruityServiceImpl implements ISecurityService {
	@Autowired
	private ProtocolSelector protocolSelector;

	@Autowired
	private SecurityRepository securityRepository;

	@Autowired
	private DeviceGroupRepository deviceGroupRepository;

	@Autowired
	private SecurityMapper securityMapper;

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private SmsUtil smsUtil;

	@Autowired
	private DeviceGroupMapper deviceGroupMapper;

	/**
	 * <p>
	 * Title: getSecurityList
	 * </p>
	 * <p>
	 * Description: 获取安全人员列表
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.security.service.ISecurityService#getSecurityList(com.fire.control.system.support.protocol.security.SecurityRequestProtocol)
	 */
	@Override
	public ResponseProtocol getSecurityListByCodition(SecurityRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		int page = requestProtocol.getPage();
		int size = requestProtocol.getSize();

		Type_Role roleType = requestProtocol.getRoleType();
		requestProtocol.setRt(roleType.toString());

		PageHelper.startPage(page, size);
		List<UserResultDTO> userResultDTOList = securityMapper.getUserListByCodition(requestProtocol);

		if (userResultDTOList.size() > 0 && userResultDTOList != null) {
			response.setData(
					ResultPageUtil.resultPage(new PageInfo<UserResultDTO>(userResultDTOList), userResultDTOList));
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("数据返回成功!");
		} else {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("成功调取但无数据!");
		}
		return response;
	}

	/**
	 * @author liuxincheng
	 * @Title: buildPageRequest
	 * @Description: TODO(构建分页请求)
	 * @param @param
	 *            pageNumber
	 * @param @param
	 *            pagzSize
	 * @param @return
	 *            设定文件
	 * @return PageRequest 返回类型
	 * @throws null
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize) {
		return new PageRequest(pageNumber - 1, pagzSize, null);
	}

	/**
	 * <p>
	 * Title: saveSecurityOr
	 * </p>
	 * <p>
	 * Description:添加管理员
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.security.service.ISecurityService#saveSecurityOr(com.fire.control.system.support.protocol.security.SecurityRequestProtocol)
	 */
	@Override
	public ResponseProtocol addSecurityOr(SecurityRequestProtocol requestProtocol, UserDTO u) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		User user = securityRepository.findOne(u.getUserId());
		User parmUser = requestProtocol.getUser();

		// 判断输入账号是否唯一
		List<User> validateUser = userMapper.getUserByLoginName(parmUser.getLoginName());

		if (validateUser != null && validateUser.size() > 0) {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("该用户已经存在");
			return response;
		}

		Company company = user.getCompany();
		Type_Role roleType = requestProtocol.getRoleType();
		Role r = roleMapper.findById(roleType.getId());

		// 判断当前是添加安全管理员还是安全巡检员
		List<String> deviceGroupIds = null;
		if ("anquanxunjianyuan".equals(roleType.getId())) {
			parmUser.setParentid(u.getUserId());
		} else {
			deviceGroupIds = JSONUtil.toList(requestProtocol.getDeviceGroupId(), String.class);
			parmUser.setParentid(null);
		}

		parmUser.setId(UUID.randomUUID().toString());
		parmUser.setCreateTime(new Date());
		parmUser.setCompany(company);
		parmUser.setUserType(Type_User.user.toString());
		parmUser.setEnable(true);

		// 生成用户密码
		String passWord = XdaoPassword.getPassword();
		parmUser.setPassword(XdaoPassword.encrypt(passWord));

		// 发送密码给用户
		smsUtil.sendSmsPwd(parmUser.getTelNumber(), parmUser.getLoginName(), passWord);

		User returnUser = securityRepository.save(parmUser);

		// 添加设备组用户关联
		if (deviceGroupIds != null && deviceGroupIds.size() > 0) {
			for (String id : deviceGroupIds) {
				securityMapper.addUserDeviceGroup(returnUser.getId(), id);
			}
		}

		// 添加用户角色关联
		roleMapper.addUserRole(returnUser.getId(), r.getId());
		if (!returnUser.equals(null)) {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("管理员添加成功!");
			response.setData(returnUser);
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("管理员添加失败!");
		}
		return response;
	}

	/**
	 * <p>
	 * Title: updateSecurityOrInfo
	 * </p>
	 * <p>
	 * Description: 修改安全管理员信息
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.security.service.ISecurityService#updateSecurityOrInfo(com.fire.control.system.support.protocol.security.SecurityRequestProtocol)
	 */
	@Override
	public ResponseProtocol updateSecurityOrInfo(SecurityRequestProtocol requestProtocol, UserDTO user) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		Collection<User> userList = new ArrayList<User>();
		User u = null;

		String[] ids = requestProtocol.getId();

		List<String> deviceGroupIds = JSONUtil.toList(requestProtocol.getDeviceGroupId(), String.class);

		for (String id : ids) {
			u = userRepository.findOne(id);
			userList.add(u);
		}

		Company c = u.getCompany();

		User paramUser = requestProtocol.getUser();

		for (User usr : userList) {
			usr.setUser(paramUser);
			usr.setCompany(c);
			usr.setPassword(u.getPassword());
			usr.setUpdateTime(new XdaoDate());
		}

		List<User> returnUser = securityRepository.save(userList);

		// 添加用户设备组关联
		if (deviceGroupIds != null && deviceGroupIds.size() > 0) {
			for (String id : deviceGroupIds) {
				for (User us : returnUser) {
					securityMapper.addUserDeviceGroup(us.getId(), id);
				}
			}
		}

		if (!returnUser.isEmpty() && returnUser.size() > 0) {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("用户信息修改成功!");
			response.setData(returnUser);
			response.setDate(new XdaoDate());
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("用户信息修改失败!");
			response.setDate(new XdaoDate());
		}
		return response;
	}

	/**
	 * <p>
	 * Title: switchSecurityOrStatus
	 * </p>
	 * <p>
	 * Description: 转换管理员状态
	 * </p>
	 * 
	 * @param requestProtocol
	 * @param user
	 * @return
	 * @see com.fire.control.system.module.security.service.ISecurityService#switchSecurityOrStatus(com.fire.control.system.support.protocol.security.SecurityRequestProtocol,
	 *      com.fire.control.system.dto.UserDTO)
	 */
	@Override
	public ResponseProtocol switchSecurityOrStatus(SecurityRequestProtocol requestProtocol, UserDTO user) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		String userId = requestProtocol.getuId();
		String enable = requestProtocol.getEnable();

		int i = userMapper.updateUserInfo(userId, Boolean.valueOf(enable));

		if (i != 0) {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("状态修改成功!");
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("状态修改失败!");
		}
		return response;
	}

	/**
	 * <p>
	 * Title: deleteSecurityOrInfo
	 * </p>
	 * <p>
	 * Description: 删除选中安全管理员
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.security.service.ISecurityService#deleteSecurityOrInfo(com.fire.control.system.support.protocol.security.SecurityRequestProtocol)
	 */
	@Override
	public ResponseProtocol deleteSecurityOrInfo(SecurityRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		int n = 0;
		User deleteUser = null;
		List<String> idList = JSONUtil.toList(requestProtocol.getuId(), String.class);
		List<User> securityUserList = securityRepository.findAll(idList);

		for (User u : securityUserList) {
			u.setStatus(false);
			deleteUser = securityRepository.saveAndFlush(u);
			n++;
		}

		if (n <= 0) {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("删除失败!");
			response.setDate(new XdaoDate());
		} else {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("删除成功!");
			response.setDate(new XdaoDate());
		}
		return response;
	}

	/**
	 * <p>
	 * Title: getDeviceGroup
	 * </p>
	 * <p>
	 * Description: 获得设备组
	 * </p>
	 * 
	 * @param requestProtocol
	 * @param user
	 * @return
	 * @see com.fire.control.system.module.security.service.ISecurityService#getDeviceGroup(com.fire.control.system.support.protocol.security.SecurityRequestProtocol,
	 *      com.fire.control.system.dto.UserDTO)
	 */
	@Override
	public ResponseProtocol getDeviceGroup(SecurityRequestProtocol requestProtocol, UserDTO user) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		User u = userRepository.findOne(user.getUserId());
		Collection<DeviceGroup> deviceGroup = u.getDeviceGroups();

		if (deviceGroup != null && deviceGroup.size() > 0) {
			response.setData(deviceGroup);
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("数据返回成功!");
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("查询失败!");
		}
		return response;
	}

	/**
	 * <p>
	 * Title: getSecuritOrDetail
	 * </p>
	 * <p>
	 * Description: 通过Id获得该人员详细信息
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.security.service.ISecurityService#getSecuritOrDetail(com.fire.control.system.support.protocol.security.SecurityRequestProtocol)
	 */
	@Override
	public ResponseProtocol getSecuritOrDetail(SecurityRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		String userId = requestProtocol.getuId();
//		User u = userRepository.findOne(requestProtocol.getuId());
		UserInfo u = userMapper.findOneById(userId);

		if (u != null) {
			String region = u.getAreaAddr();
			if(region != null) {
				u.setRegion(region.split(","));
			}
			List<SelectGroupDTO> deviceGroups = deviceGroupMapper.getGroupsByUserId(userId);
			u.setDeviceGroups(deviceGroups);
			response.setData(u);
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("数据返回成功!");
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("查询失败!");
		}
		return response;
	}

	/**
	 * <p>
	 * Title: getParentSecuritOr
	 * </p>
	 * <p>
	 * Description: 获取该人员的上级管理员
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.security.service.ISecurityService#getParentSecuritOr(com.fire.control.system.support.protocol.security.SecurityRequestProtocol)
	 */
	@Override
	public ResponseProtocol getParentSecuritOr(SecurityRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		String userId = requestProtocol.getuId();

		List<User> parentUser = securityMapper.getParentUser(userId);

		if (!parentUser.isEmpty() && parentUser.size() > 0) {
			response.setData(parentUser);
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("数据返回成功!");
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("数据返回失败!");
		}
		return response;
	}

	/**
	 * <p>
	 * Title: getSecurityOrPassWord
	 * </p>
	 * <p>
	 * Description: 获取安全人员密码
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.security.service.ISecurityService#getSecurityOrPassWord(com.fire.control.system.support.protocol.security.SecurityRequestProtocol)
	 */
	@Override
	public ResponseProtocol getSecurityOrPassWord(SecurityRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		String userId = requestProtocol.getuId();

		User u = userMapper.getById(userId);

		boolean flag = smsUtil.sendSmsPwd(u.getTelNumber(), u.getLoginName(), XdaoPassword.decrypt(u.getPassword()));

		if (flag) {
			ResponseMessage.CODE_200.messageToProtocol(response).setMessage("密码获取成功!");
		} else {
			ResponseMessage.CODE_400.messageToProtocol(response).setMessage("密码获取失败!");
		}
		return response;
	}

}
